package com.allen.admin.service.server.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.allen.admin.service.common.domain.AdminRolePerm;
import com.allen.admin.service.common.service.AdminRolePermService;
import com.allen.admin.service.server.manager.impl.AdminRolePermManager;
import com.xxx.config.ModelResult;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;


@Service("adminRolePermService")
public class AdminRolePermServiceImpl implements AdminRolePermService {
	
	private final static Logger logger = LoggerFactory.getLogger(AdminRolePermServiceImpl.class);
	
	@Autowired
	private TransactionTemplate transactionTemplate;
	@Autowired
	private AdminRolePermManager adminRolePermManager;

	@Override
	public ModelResult<List<AdminRolePerm>> query(Integer roleId) {
		ModelResult<List<AdminRolePerm>> resultModelResult = new ModelResult<>();
		List<AdminRolePerm> list = adminRolePermManager.select(roleId);
		resultModelResult.withModel(list);
		return resultModelResult;
	}
	
	@Override
	public ModelResult<List<String>> queryCodes(List<Integer> roleIds) {
		ModelResult<List<String>> resultModelResult = new ModelResult<>();
		List<String> list  = new ArrayList<>();

		if (CollectionUtils.isEmpty(roleIds)) {
			logger.error("Query codes fail roleIds is empty");
			return resultModelResult.withModel(list);
		}
		list = adminRolePermManager.selectCodesByRoles(roleIds);
		return resultModelResult.withModel(list);
	}
	
	@Override
	public ImmutablePair<Boolean, String> auth(Integer roleId, List<String> perms) {

		logger.info("角色权限 授权 [{}] 开始", roleId);
		try {
			transactionTemplate.execute(new TransactionCallbackWithoutResult(){

				@Override
				protected void doInTransactionWithoutResult(TransactionStatus status) {
				adminRolePermManager.delete(roleId);
				if (CollectionUtils.isNotEmpty(perms)) {
					perms.stream().forEach(p->{
						AdminRolePerm arp = new AdminRolePerm();
						arp.setRoleId(roleId);
						arp.setPermCode(p);
						adminRolePermManager.insert(arp);
					});
				}
				}
				
			});
		} catch (TransactionException e) {
			logger.error("角色权限 授权 ["+roleId+"] 异常", e);
			return ImmutablePair.of(Boolean.FALSE, "角色权限，授权异常");
		}
		
		logger.info("角色权限 授权 [{}] 成功", roleId);
		return ImmutablePair.of(Boolean.TRUE, null);
	}
	
}
